<template>
  <b-container class="timeCard" fluid>
    <div style="text-align: center">
      <b-row>
        <h6>
          {{ $store.state.time.year }}年{{ $store.state.time.month }}月{{
            $store.state.time.day
          }}日 {{ $store.state.time.week }}
        </h6>
      </b-row>
      <b-row>
        <h4>
          {{ $store.state.time.hour }}:{{ $store.state.time.minute }}:{{
            $store.state.time.second
          }}
        </h4>
      </b-row>
      <b-row>
        <h6 style="color: rgba(44, 185, 228, 0.842)">
          {{ oneMessage }} <br />
          {{ messageFrom }}
        </h6>
      </b-row>
    </div>
  </b-container>
</template>

<script>
import axios from "axios";
export default {
  name: "TimeClock",
  data() {
    return {
      //时钟js
      time: {
        year: "2077",
        month: "什么",
        day: "什么",
        hour: "什么",
        minute: "多少",
        second: "0",
        week: "星期几",
      },
      //随机二次元图片当背景
      randomPicSrc: "https://www.hlapi.cn/api/ecy1",
      //一言api
      oneMessage: "获取中",
      messageFrom: "获取中",
    };
  },
  methods: {
    //时钟js
    currentTime() {
      setInterval(this.formatDate, 0);
    },
    //时钟js
    formatDate() {
      var date = new Date();
      var year = date.getFullYear(); // 年
      var month = date.getMonth() + 1; // 月
      var day = date.getDate(); // 日
      var week = date.getDay(); // 星期
      var weekArr = [
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
      ];
      var hour = date.getHours(); // 时
      hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
      var minute = date.getMinutes(); // 分
      minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
      var second = date.getSeconds(); // 秒
      second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
      this.time.year = `${year}`;
      this.time.month = `${month}`;
      this.time.day = `${day}`;
      this.time.hour = `${hour}`;
      this.time.minute = `${minute}`;
      this.time.second = `${second}`;
      this.time.week = `${weekArr[week]}`;
      this.$store.commit("setTime", this.time);
    },
    //一言api
    getOneMessage() {
      axios
        .get("api")
        .then((res) => {
          console.log("-----------",res);
          this.oneMessage = res.data.hitokoto;
          this.messageFrom = "《" + res.data.from+'》';
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
  mounted() {
    //时钟js
    this.currentTime();
    //一言api
    this.getOneMessage();
  },
  // 销毁定时器
  beforeDestroy() {
    //时钟js
    if (this.formatDate) {
      clearInterval(this.formatDate); // 在Vue实例销毁前，清除时间定时器
    }
  },
};
</script>

<style scoped lang="css">
.timeCard {
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  padding: 5%;
  margin-bottom: 2.5%;
}
</style>